


        
new Vue({
    el:"#app",
    data(){
        return{
            me:{},
            other:{},
            id_me:"",
            id_to:"",
            send_message:"",
            im:{},
            goeasy:{}
        }
    },
    methods:{
        // 获取自己的信息
    // 获取用户详细信息
        getMe() {
            let _this = this
            axios({
                method: "get",
                url: "http://localhost:8088/users/me",
                headers: {
                authorization: localStorage.authorization
                }
            }).then(function (resp) {
                _this.me = resp.data.data
                console.log(resp.data.data.profile)

            })
            },

        // 获取对方信息
        getOther(){
            let _this=this
            axios({
              method:"get",
              url: "http://localhost:8088/users/select/3/"+_this.id_to,
              headers:{
                authorization:localStorage.authorization
              }
            }).then(function(resp){
              _this.other=resp.data.data[0]
              console.log("对方的信息：")
              console.log(_this.other.username)
              
            })
        },


        // 获取历史消息
        getHistory(){
           let _this=this
            this.im.history({
                userId: this.id_to,  //对方userId
                lastTimestamp: null, //上次查询结果里最后一条消息的时间戳，首次查询传入null即可
                limit: 10, //可选项，返回的消息条数，默认为10条，最多30条
                onSuccess: function (result) { 
                    
                    history_content=result.content
                    console.log(history_content)
                    for(let i=0; i<history_content.length;i++){
                      content_ok=history_content[i]
                      if(content_ok.senderId==_this.id_to){
                        $('#talk_list').append('<li class="left_word"><img style="width: 48px; border-radius:50%;height: 48px;"  src='+_this.other.profile+' /> <span>' + content_ok.payload.text + '</span></li>')
                      }else if(content_ok.senderId==_this.id_me){
                        $('#talk_list').append('<li class="right_word"><img style="width: 48px; border-radius:50%;height: 48px;" src='+_this.me.profile+' /> <span>' + content_ok.payload.text + '</span></li>')
            
                      }
                    resetui();
                      
                    }
            
                   
            
                },
                onFailed: function (error) { //获取失败
                    console.log("Failed to query private message, code:" + error.code + " content:" + error.content);
                },
            });
            
        },
        // 发送消息
        send(){
            var text = $('#ipt').val().trim()
            if (text.length <= 0) {
                return $('#ipt').val('')
            }
            // 如果用户输入了聊天内容，则将聊天内容追加到页面上显示
            $('#talk_list').append('<li class="right_word"><img style="width: 48px; border-radius:50%;height: 48px;"src='+this.me.profile+' /> <span>' + text + '</span></li>')
            $('#ipt').val('')
                // 重置滚动条的位置
            resetui();
            //给服务器发送消息
            let textMessage = this.im.createTextMessage({
                text:this.send_message, //消息内容
                to : {
                    type : GoEasy.IM_SCENE.PRIVATE,   //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
                    id : this.id_to,
                    data:{"avatar":"/www/xxx.png","nickname":"Neo"} //好友扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
                }
            });

            
                //发送消息
            this.im.sendMessage({
                message:textMessage,
                onSuccess: function (message) { //发送成功
                    console.log("Private message sent successfully.", message);
                },
                onFailed: function (error) { //发送失败
                    console.log('Failed to send private message，code:' + error.code +' ,error ' + error.content);
                }
                });


        },
        init(){
            // 初始化
            this.goeasy  = GoEasy.getInstance({
            host:"hangzhou.goeasy.io",  //若是新加坡区域：singapore.goeasy.io
            appkey:"BC-c8b07025438443e2963028be1d94a8de",
            modules:['im']//根据需要，传入‘pubsub’或'im’，或数组方式同时传入
            });
            this.im=this.goeasy.im
            //建立连接
            this.goeasy.connect({
                id:localStorage.id, //pubsub选填，im必填，最大长度60字符
                data:{"avatar":"/www/xxx.png","nickname":"Neo"}, //必须是一个对象，pubsub选填，im必填，最大长度300字符，用于上下线提醒和查询在线用户列表时，扩展更多的属性
                onSuccess: function () {  //连接成功
                    console.log("GoEasy connect successfully.") //连接成功
                },
                onFailed: function (error) { //连接失败
                    console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
                },
                onProgress:function(attempts) { //连接或自动重连中
                    console.log("GoEasy is connecting", attempts);
                }
                });
                this.im.markPrivateMessageAsRead({
                    userId:this.id_to,  //聊天对象的userId
                    onSuccess: function () { //标记成功
                        console.log("Marked as read successfully."); 
                        
                    },
                    onFailed: function (error) { //标记失败
                        console.log("Failed to mark as read, code:" + error.code + " content:" + error.content);
                    }   
                });
              },
        getValue(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
        }
    },
    mounted(){
       this.id_me=this.getValue("me");
       this.id_to=this.getValue("to");
       this.init()

       this.getMe()
       this.getOther()
        this.getHistory()
        


        let _this=this
        


        
        var onPrivateMessageReceived = function(message) {
    
                _this.im.markPrivateMessageAsRead({
                userId:_this.id_to,  //聊天对象的userId
                onSuccess: function () { //标记成功
                    console.log("Marked as read successfully."); 
                },
                onFailed: function (error) { //标记失败
                    console.log("Failed to mark as read, code:" + error.code + " content:" + error.content);
                }   
            });
        
            if(message.receiverId==_this.id_me&&message.senderId==_this.id_to){
                setTimeout(function(){
                    console.log("测试" + JSON.stringify(message.payload.text));
                    $('#talk_list').append('<li class="left_word"><img style="width: 48px; border-radius:50%;height: 48px;"  src='+_this.other.profile+' /> <span>' + message.payload.text + '</span></li>')
                    resetui();
                },2)
                
            }
               
            };
        

        
          //监听和接收单聊消息
          this.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);



            

          this.im.latestConversations({
              onSuccess: function (result) { 

                console.log(result)
    
              },
              onFailed: function (error) { //获取失败
                  console.log("Failed to get the latest conversations, code:" + error.code + " content:" + error.content);
              },
          });

          var onConversationsUpdated = function(conversations) {
            //更新后的最新会话列表
            console.log(conversations)
    };

    //监听会话列表更新
    this.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated);


    }
})









